package com.xncoding.websocket.WebMvc.demoStomp;


import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
@Order(0)
public class WSTokenInterceptor implements ChannelInterceptor {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (Objects.isNull(accessor)) {
            throw new MessageDeliveryException("TOKEN为空");
        }
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            List<String> nativeHeader = accessor.getNativeHeader("token");
            if (CollectionUtils.isEmpty(nativeHeader)) {
                throw new MessageDeliveryException("TOKEN为空");
            }
            String token = nativeHeader.get(0);
            if (StringUtils.isEmpty(token)) {
                throw new MessageDeliveryException("TOKEN为空");
            }
            //这里要解析Token，本例就不写这一段了
            if ("leo3".equals(token)) {
                throw new MessageDeliveryException("TOKEN错误");
            }
            log.info("初次连接，Token:{}", token);
            accessor.setUser(() -> token);
            return message;
        } else if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
            log.info("订阅：{},{}", Objects.requireNonNull(accessor.getUser()).getName(), accessor.getDestination());
        } else if (StompCommand.UNSUBSCRIBE.equals(accessor.getCommand())) {
            log.info("取消订阅：{},{}", Objects.requireNonNull(accessor.getUser()).getName(), accessor.getDestination());
        } else if (StompCommand.SEND.equals(accessor.getCommand())) {
            log.info("发送：{},{}", Objects.requireNonNull(accessor.getUser()).getName(), accessor.getDestination());
        } else if (StompCommand.DISCONNECT.equals(accessor.getCommand())) {
            log.info("断开连接：{}", Objects.requireNonNull(accessor.getUser()).getName());
        }
        return message;
    }
}